package com.itheima.solr.test;

import com.itheima.solr.pojo.Item;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.junit.Test;

import java.util.List;

public class SolrTestQuery {
    /**
     *  以SolrDocument方式返回
     * @throws SolrServerException
     */
    @Test
    public void test() throws SolrServerException {
        //连接服务器
        HttpSolrServer solrServer = new HttpSolrServer("HTTP://127.0.0.1:8080/solr/test");
        //创建查询对象：SolrQuery
        SolrQuery solrQuery = new SolrQuery("title:机");

        //执行查询，获取响应
        QueryResponse response = solrServer.query(solrQuery);

        //获取查询结果
        SolrDocumentList documents = response.getResults();

        for (SolrDocument document : documents) {
            System.out.println(document.getFieldValue("id"));
            System.out.println(document.getFieldValue("title"));
            System.out.println(document.getFieldValue("price"));
        }

    }

    /**
     * 以javaBean方式返回
     * @throws SolrServerException
     */
    @Test
    public void test2() throws SolrServerException {
        //连接服务器
        HttpSolrServer solrServer = new HttpSolrServer("http://127.0.0.1:8080/solr/test");
        //创建查询对象：SolrQuery
        SolrQuery solrQuery = new SolrQuery("title:手机");

        //执行查询，获取响应
        QueryResponse response = solrServer.query(solrQuery);

        //获取查询结果
        // 获取查询结果,指定实体类的类型，返回实体类的集合
        List<Item> beans = response.getBeans(Item.class);

        System.out.println("本次一共搜到："+beans.size()+"条数据");
        for (Item item : beans) {
            System.out.println(item.getId());
            System.out.println("title:"+item.getTitle());
            System.out.println("price:" + item.getPrice());
        }

    }


}
